package cn.stronglink.asset.module.inventory.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import cn.stronglink.asset.model.Inventory;
import cn.stronglink.asset.model.InventoryDetail;
import cn.stronglink.asset.model.InventorySheet;
import cn.stronglink.asset.model.InventorySheetDetail;
import cn.stronglink.asset.model.InventoryTime;
import cn.stronglink.asset.model.RfidState;
import cn.stronglink.asset.module.assetmanage.itasset.mapper.ItassetMapper;
import cn.stronglink.asset.module.inventory.mapper.InventoryMapper;
import cn.stronglink.asset.module.inventory.vo.InventoryVo;
import cn.stronglink.asset.module.rfidState.mapper.RfidStateMapper;
import cn.stronglink.suite.core.schedulder.TaskScheduled;
import cn.stronglink.suite.core.schedulder.TaskScheduled.JobType;
import cn.stronglink.suite.core.schedulder.TaskScheduled.TaskType;
import cn.stronglink.suite.core.support.scheduler.SchedulerManager;
import cn.stronglink.suite.core.util.PropertiesUtil;
import cn.stronglink.suite.core.util.WebUtil;

@Service
@Transactional(rollbackFor=Exception.class) 
public class InventoryService {

	@Autowired
	private InventoryMapper inventoryMapper;
	@Autowired
	private RfidStateMapper rfidStateMapper;
	@Autowired
	private ItassetMapper itassetMapper;
	@Autowired
	private SchedulerManager schedulerManager;


	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Page<InventoryVo> queryList(Page<InventoryVo> page, Map<String, Object> params) {
		List<InventoryVo> list =inventoryMapper.queryList(page,params);
		if (list != null && list.size() > 0) {
			for (InventoryVo in : list) {
				List<InventoryTime> timeList = inventoryMapper
						.getInventoryTimes(in.getId());
				String patrolTime = "";
				String[] day1 = { "周一", "周二", "周三", "周四", "周五", "周六", "周日" };
				if (timeList != null && timeList.size() > 0) {
					for (int i = 0; i < timeList.size(); i++) {
						InventoryTime ppt = timeList.get(i);
						if (in.getCycleType() == 2) {
							patrolTime += day1[ppt.getDay() - 1];
						} else if (in.getCycleType() == 3) {
							patrolTime += ppt.getDay() + "日";
						}
						patrolTime += ppt.getStartTime();
						if (i != timeList.size() - 1) {
							patrolTime += ";";
						}
					}
				}
				in.setInventoryTime(patrolTime);
			}
		}
		page.setRecords(list);
		return page;	
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public InventoryVo qryById(Long id) {
		InventoryVo vo = inventoryMapper.qryById(id);
		List<InventoryTime> timeList = inventoryMapper.getInventoryTimes(id);
		vo.setInventoryTimes(timeList);
		List<Long> rackIds =inventoryMapper.qryRackIdsById(id);
		List<String> rackIdsString=new ArrayList<String>();
		if(rackIds!=null&&rackIds.size()>0){
			for(Long child:rackIds){
				rackIdsString.add(child.toString());
			}
		}
		vo.setRackIdsString(rackIdsString);
		return vo;
	}


	public int create(InventoryVo inventory) {
		inventory.setId(IdWorker.getId());
		inventory.setStatus(1);
		inventory.setCreateBy(WebUtil.getCurrentUser());
		inventory.setCreateTime(new Date());
		int count =inventoryMapper.insertInventory(inventory);	
		if (inventory.getInventoryTimes() != null && inventory.getInventoryTimes().size() > 0) {
			for (InventoryTime time : inventory.getInventoryTimes()) {
				time.setInventoryId(inventory.getId());
				time.setId(IdWorker.getId());
			}
			HashMap<String,Object> map=new HashMap<String,Object>();
			map.put("inventoryTimes", inventory.getInventoryTimes());
			inventoryMapper.insertInventoryTime(map);
		}
		for(Long rackId :inventory.getRackIds()){
			InventoryDetail detail = new InventoryDetail();
			detail.setId(IdWorker.getId());
			detail.setRackId(rackId);
			detail.setInventoryId(inventory.getId());
			detail.setCreateBy(WebUtil.getCurrentUser());
			detail.setCreateTime(new Date());
			insertInventoryDetail(detail);
		}
		getTaxk(inventory);
		return count;
		
	}


	private void getTaxk(InventoryVo inventory) {
		if (inventory.getInventoryTimes() != null && inventory.getInventoryTimes().size() > 0) {
			for (InventoryTime time : inventory.getInventoryTimes()) {
				int hh=0,ss=0;
				String hs[]=time.getStartTime().split(":");
				if(hs!=null&&hs.length>0){
					hh=hs[0]!=null?Integer.parseInt(hs[0]):0;
					ss=hs[1]!=null?Integer.parseInt(hs[1]):0;
					String taskCron="";
					if(inventory.getCycleType()==1){
						//每天
						taskCron="0 "+ss+" "+hh+" * * ? *";
					}else if(inventory.getCycleType()==2){
						//每周
						String[] weeks={"MON","TUES","WED","THUR","FRI","SAT","SUN"};
						taskCron="0 "+ss+" "+hh+" ? * "+weeks[time.getDay()];
					}else if(inventory.getCycleType()==3){
						//每月
						taskCron="0 "+ss+" "+hh+" "+time.getDay()+" * ?";
				    }
					//创建新的定时器任务
					TaskScheduled task = new TaskScheduled();
					task.setTaskName(time.getId().toString());
					task.setTaskGroup("inventory");
					task.setStatus("1");
					//taskCron="0 0/1 * * * ?";     0 30,39 12 7,10 12 ? 2017      0 30 11 7 12 ? 2017
					task.setTaskCron(taskCron);
					task.setTaskDesc(inventory.getInventoryName());
					task.setJobType(JobType.job);
					task.setTaskType(TaskType.local);
					task.setTargetObject("inventoryService");
					task.setTargetMethod("inventoryPlanQrtzRu");
					task.setArgs(time.getId());
					schedulerManager.updateTask(task);
				}
			}
		}
	}
	/**
	 * RU1000
	 * @param id
	 */
	public void inventoryPlanQrtzRu(Long id){
		System.out.println(id+"$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
		Inventory inventory =inventoryMapper.qryByTimeId(id);
		inventory.setStatus(2);
		inventoryMapper.updateInventoryState(inventory);
		
		List<InventoryDetail> dList =inventoryMapper.quryInDetail(inventory.getId());
		
		//判断该盘点计划是自动盘还是手动盘
		if(inventory.getInventoryType()==2) {
			if(dList!=null&&dList.size()>0){
				//添加盘点单
				InventorySheet sheet = new InventorySheet();
				sheet.setId(IdWorker.getId());
				sheet.setStatus(1);
				sheet.setExecuteTime(new Date());
				sheet.setInventoryId(inventory.getId());
				sheet.setCreateTime(new Date());
				String dateName= new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
				sheet.setInventorySheetName(inventory.getInventoryName()+dateName);
				inventoryMapper.insertInventorySheet(sheet);
				
				int rackUOrientation = PropertiesUtil.getInt("rackUOrientation", 1);
				
				for(InventoryDetail detail:dList){
					//循环查询出每个机柜内的设备，插入到盘点单详情里  (台账里的设备)
					List<InventorySheetDetail> shDetailList = null;
					if(rackUOrientation==0) {
						shDetailList = getInventoryAssetsUfromAboveDown(detail.getRackId());
					}else{
						shDetailList = getInventoryAssets(detail.getRackId());
					}
					if(shDetailList!=null&&shDetailList.size()>0){
						for(InventorySheetDetail shdetail:shDetailList){
							shdetail.setId(IdWorker.getId());
							shdetail.setInventorySheetId(sheet.getId());
							shdetail.setLedgerCabinet(shdetail.getRackId());
							shdetail.setStatus(1);
							shdetail.setIsHandle(1);
						}
					}
					//批量插入盘点单详情
					if(shDetailList!=null&&shDetailList.size()>0){
						HashMap<String,Object> map = new HashMap<String,Object>();
						map.put("shDetailList", shDetailList);
						inventoryMapper.insertInventorySheetDetail(map);
					}
					
				}
			}
		} else {
			//添加盘点单
			InventorySheet sheet = new InventorySheet();
			sheet.setId(IdWorker.getId());
			sheet.setStatus(2);
			sheet.setExecuteTime(new Date());
			sheet.setInventoryId(inventory.getId());
			sheet.setCreateTime(new Date());
			String dateName= new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			sheet.setInventorySheetName(inventory.getInventoryName()+dateName);
			inventoryMapper.insertInventorySheet(sheet);
			
			List<String> rackList = new ArrayList<String>();
			if(dList!=null&&dList.size()>0){
				for(InventoryDetail d:dList){
					if(!"".equals(d.getRackConverCode())&&d.getRackConverCode()!=null){
						rackList.add(d.getRackConverCode());
					}
				}
			}
			List<RfidState> inventoryRfidList = new ArrayList<RfidState>();
			if(rackList.size()>0){
				//已盘点的rfid记录
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("rackCodeList", rackList);
				System.out.println(JSON.toJSON(rackList));
				inventoryRfidList = rfidStateMapper.getRfidStateByRack(map);	
			}
			List<RfidState> exsitRfidList = new ArrayList<RfidState>();//应盘到的标签(即台账里有的标签)
			//获取盘点计划详情列表
			 if(dList!=null&&dList.size()>0){
				 int rackUOrientation = PropertiesUtil.getInt("rackUOrientation", 1);
				for(InventoryDetail detail:dList){
					//循环查询出每个机柜内的设备，插入到盘点单详情里  (台账里的设备)
					List<InventorySheetDetail> shDetailList = null;
					if(rackUOrientation == 0) {
						shDetailList = getInventoryAssetsUfromAboveDown(detail.getRackId());
					}else {
						shDetailList = getInventoryAssets(detail.getRackId());
					}
					if(shDetailList!=null&&shDetailList.size()>0){
					   for(InventorySheetDetail shdetail:shDetailList){
							shdetail.setId(IdWorker.getId());
							shdetail.setInventorySheetId(sheet.getId());
							shdetail.setStatus(4);
							shdetail.setIsHandle(1);
							shdetail.setCreateTime(new Date());
							if(!"".equals(shdetail.getRfidNo())&&shdetail.getRfidNo()!=null&&!"".equals(shdetail.getRackConverCode())) {
								RfidState rfidState = new RfidState();
								rfidState.setRfidNo(shdetail.getRfidNo());
								rfidState.setU(shdetail.getLedgerU());
								rfidState.setRackConverCode(shdetail.getRackConverCode());
								//应盘到的标签(即台账里有的标签)
								exsitRfidList.add(rfidState);
							}
						}
					}
					//批量插入盘点单详情
					if(shDetailList!=null&&shDetailList.size()>0){
						HashMap<String,Object> map = new HashMap<String,Object>();
						map.put("shDetailList", shDetailList);
						inventoryMapper.insertInventorySheetDetail(map);
					}
				}
			 }
				//比对资产标签状态表（rfid_state）读取资产标签状态表中资产的位置和台帐的位置做比对，生成盘点报告
				compareInventorySheet(inventoryRfidList,exsitRfidList,sheet.getId());
		}
		
	}
	
	
	private List<InventorySheetDetail> getInventoryAssetsUfromAboveDown(Long rackId) {
		return inventoryMapper.getInventoryAssetsUfromAboveDown(rackId);
	}

	/**
	 * 2.4g 
	 * @param id
	 */
	public void inventoryPlanQrtz(Long id){
		System.out.println(id+"$$$$$$$$$$$$盘点开始$$$$$$$$$$$$$$$$");
		Inventory inventory =inventoryMapper.qryById(id);
		
		//已盘点的2.4G记录
		List<RfidState> inventoryRfidList = rfidStateMapper.getAllRfidState();		
		List<RfidState> exsitRfidList = new ArrayList<RfidState>();//应盘到的标签(即台账里有的标签)
				
		//添加盘点单
		InventorySheet sheet = new InventorySheet();
		sheet.setId(IdWorker.getId());
		sheet.setStatus(1);
		sheet.setExecuteTime(inventory.getBeginTime());
		sheet.setInventoryId(inventory.getId());
		sheet.setCreateTime(new Date());
		String dateName= new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		sheet.setInventorySheetName(inventory.getInventoryName()+dateName);
		inventoryMapper.insertInventorySheet(sheet);
			
		//将盘点计划更新为已完成
		inventory.setStatus(2);
		inventoryMapper.updateInventoryState(inventory);		
		
		//获取盘点计划详情列表
		List<InventoryDetail> dList =inventoryMapper.quryInDetail(inventory.getId());
		 if(dList!=null&&dList.size()>0){
			int rackUOrientation = PropertiesUtil.getInt("rackUOrientation", 1);
			for(InventoryDetail detail:dList){
				//循环查询出每个机柜内的设备，插入到盘点单详情里  (台账里的设备)
				List<InventorySheetDetail> shDetailList = null;
				if(rackUOrientation == 0) {
					shDetailList = getInventoryAssetsUfromAboveDown(detail.getRackId());
				}else {
					shDetailList = getInventoryAssets(detail.getRackId());
				}
				if(shDetailList!=null&&shDetailList.size()>0){
				   for(InventorySheetDetail shdetail:shDetailList){
						shdetail.setId(IdWorker.getId());
						shdetail.setRfidNo(shdetail.getCode24g());
						shdetail.setInventorySheetId(sheet.getId());
						shdetail.setStatus(4);
						shdetail.setIsHandle(1);
						shdetail.setCreateTime(new Date());
						if(!"".equals(shdetail.getCode24g())&&shdetail.getCode24g()!=null) {
							RfidState rfidState = new RfidState();
							rfidState.setRfidNo(shdetail.getCode24g());
							//应盘到的标签(即台账里有的标签)
							exsitRfidList.add(rfidState);
						}
					}
				}
				//批量插入盘点单详情
				HashMap<String,Object> map = new HashMap<String,Object>();
				map.put("shDetailList", shDetailList);
				inventoryMapper.insertInventorySheetDetail(map);
			}
		 }		
				
		//比对资产标签状态表（rfid_state）读取资产标签状态表中资产的位置和台帐的位置做比对，生成盘点报告
		compareInventorySheet24g(inventoryRfidList,exsitRfidList,id,sheet.getId());
		
	}
	/**
	 * 2.4g 
	 * @param id
	 */
	private void compareInventorySheet24g(List<RfidState> inventoryRfidList, List<RfidState> exsitRfidList, Long inventoryId, Long inventorySheetId) {
        // 不同
		Collection<String> diffentReturn = new LinkedList<String>();		
		//相同
		Collection<String> asReturn = new LinkedList<String>();
		
	//	Collection<RfidState> overData = new HashSet<RfidState>();
		Collection<RfidState> lossData = new HashSet<RfidState>();
		Collection<RfidState> normalData = new HashSet<RfidState>();
		
		List<RfidState> max =inventoryRfidList;
		List<RfidState> min =exsitRfidList;
		if(max.size()<min.size()){
			max=exsitRfidList;
			min=inventoryRfidList;
		}
		
	     Map<String,Integer> map = new HashMap<String,Integer>(max.size());
	     for (RfidState object : max) {
	         map.put(object.getRfidNo(), 1);
	     }
	     for (RfidState object : min) {
	         if(map.get(object.getRfidNo())==null){
	        	 diffentReturn.add(object.getRfidNo());
	        	 if(max.size()<min.size()){
	        		// overData.add(object);
	        	 }else{
	        		 lossData.add(object);
	        	 }
	         }else{
	             map.put(object.getRfidNo(), 2);
	         }
	     }
	     Map<String,RfidState> inventoryRfidListmap = new HashMap<String,RfidState>(inventoryRfidList.size());
	     for (RfidState object : inventoryRfidList) {
	    	 inventoryRfidListmap.put(object.getRfidNo(), object);
	     }
	     
	     Map<String,RfidState> exsitRfidListmap = new HashMap<String,RfidState>(exsitRfidList.size());
	     for (RfidState object : exsitRfidList) {
	    	 exsitRfidListmap.put(object.getRfidNo(), object);
	     }
	     
	     for (Map.Entry<String, Integer> entry : map.entrySet()) {
	         if(entry.getValue()==1){
	        	 if(max.size()<min.size()){
	        		 lossData.add(exsitRfidListmap.get(entry.getKey()));
	        	 }
//	        	 else{
//	        		 overData.add(inventoryRfidListmap.get(entry.getKey()));
//	        	 }
	         }
	         if(entry.getValue()==2){
	        	 asReturn.add(entry.getKey());
	         }
	     }
	     
	     /**
	      * 最后再判断 相同的里边有没有差异 asReturn 
	      */
	     
	     for(Iterator<String> iter = asReturn.iterator(); iter.hasNext();){
	    	 String rfid =(String) iter.next();
	    	 normalData.add(inventoryRfidListmap.get(rfid));	    	 
	     }
 
		 //更新数据状态
		 Inventory inventory = new Inventory();
		 inventory.setId(inventoryId);
		 inventory.setStatus(3);
		 inventoryMapper.updateInventoryState(inventory);
		 
		 //更新盘亏
		 if(lossData!=null&&lossData.size()>0) {
			 HashMap<String,Object> lossMap = new HashMap<String,Object>();
			 lossMap.put("lossData", lossData);
			 lossMap.put("inventorySheetId", inventorySheetId);
			 inventoryMapper.updateInventoryLoss(lossMap);
		 }
		 
		 if(normalData!=null&&normalData.size()>0) {
			 //更新正常
			 HashMap<String,Object> normalMap = new HashMap<String,Object>();
			 normalMap.put("normalData", normalData);
			 normalMap.put("inventorySheetId", inventorySheetId);
			 inventoryMapper.updateInventoryNormal(normalMap);
		 }
	}
	
	private void compareInventorySheet(List<RfidState> inventoryRfidList, List<RfidState> exsitRfidList, Long inventorySheetId) {
		Collection<String> diffentReturn = new LinkedList<String>(); // 不同
		Collection<String> asReturn = new LinkedList<String>();//相同
		Collection<RfidState> overData = new HashSet<RfidState>();
		Collection<RfidState> lossData = new HashSet<RfidState>();
		Collection<RfidState> differentData = new HashSet<RfidState>();
		Collection<RfidState> normalData = new HashSet<RfidState>();
		
		List<RfidState> max =inventoryRfidList;
		List<RfidState> min =exsitRfidList;
		if(max.size()<min.size()){
			max=exsitRfidList;
			min=inventoryRfidList;
		}
	     Map<String,Integer> map = new HashMap<String,Integer>(max.size());
	     for (RfidState object : max) {
	         map.put(object.getRfidNo(), 1);
	     }
	     for (RfidState object : min) {
	         if(map.get(object.getRfidNo())==null){
	        	 diffentReturn.add(object.getRfidNo());
	        	 if(max.size()==exsitRfidList.size()&&exsitRfidList.size()!=inventoryRfidList.size()){
	        		 // 如果max<min 说明 max=bb为台账，  min=aa 为盘点 .此时盘点的不在台账中 为盘盈
	        		 overData.add(object);
	        	 }else{
	        		// 此时说明 max=aa为盘点，     min=bb 为台账    此时台账不在盘点中  为盘亏
	        		 lossData.add(object);
	        	 }
	         }else{
	             map.put(object.getRfidNo(), 2);
	         }
	     }
	     // inventoryRfidList所有
	     Map<String,RfidState> inventoryRfidListmap = new HashMap<String,RfidState>(inventoryRfidList.size());
	     for (RfidState object : inventoryRfidList) {
	    	 inventoryRfidListmap.put(object.getRfidNo(), object);
	     }
	     
	     //exsitRfidList 所有
	     Map<String,RfidState> exsitRfidListmap = new HashMap<String,RfidState>(exsitRfidList.size());
	     for (RfidState object : exsitRfidList) {
	    	 exsitRfidListmap.put(object.getRfidNo(), object);
	     }
	     
	     for (Map.Entry<String, Integer> entry : map.entrySet()) {
	         if(entry.getValue()==1){
	        	 if(max.size()==exsitRfidList.size()&&exsitRfidList.size()!=inventoryRfidList.size()){
	        		// 如果max<min 说明 max=bb为台账，  min=aa 为盘点
		        	// 此时entry.getvalue==1的 说明     盘点中没有的此时为盘亏
	        		 lossData.add(exsitRfidListmap.get(entry.getKey()));
	        	 }else{
	        		// 此时说明 max=aa为盘点，     min=bb 为台账
		        	// 此时entry.getvalue==1的 说明     台账中没有的 此时为盘盈
	        		 overData.add(inventoryRfidListmap.get(entry.getKey()));
	        	 }
	         }
	         if(entry.getValue()==2){
	        	 asReturn.add(entry.getKey());
	         }
	     }
	     
	     /**
	      * 最后再判断 相同的里边有没有差异 asReturn 
	      */	     
	     for(Iterator<String> iter = asReturn.iterator(); iter.hasNext();){
	    	 String rfid =(String) iter.next();
	    	 RfidState inventoryRfidListobj =inventoryRfidListmap.get(rfid);
	    	 RfidState exsitRfidListobj =exsitRfidListmap.get(rfid);
	    	 
	    	 if(inventoryRfidListobj.getU()!=exsitRfidListobj.getU()||!inventoryRfidListobj.getRackConverCode().equals(exsitRfidListobj.getRackConverCode())){
	    		 //差异
	    		 differentData.add(inventoryRfidListmap.get(rfid));
	    	 }else{
	    		 normalData.add(inventoryRfidListmap.get(rfid));
	    	 }	    	 
	     }
		 //更新盘亏
		 if(lossData!=null&&lossData.size()>0) {
			 HashMap<String,Object> lossMap = new HashMap<String,Object>();
			 lossMap.put("lossData", lossData);
			 lossMap.put("inventorySheetId", inventorySheetId);
			 inventoryMapper.updateInventoryLoss(lossMap);
		 }		 
		 //更新盘盈
		 List<InventorySheetDetail> sheetDetail = new ArrayList<InventorySheetDetail>();
		 if(overData!=null&&overData.size()>0){
			 for(Iterator<RfidState> iter = overData.iterator(); iter.hasNext();){
		    	 RfidState obj = (RfidState) iter.next();
		    	 int count = itassetMapper.qryCountByRfidNo(obj.getRfidNo());
		    	 if(count>0){
		    		 differentData.add(obj);
		    	 }else{
		    		 RfidState roomAndRack = itassetMapper.getRoomAndRack(obj.getRackConverCode());
			    	 obj.setRackId(roomAndRack.getRackId());
			    	 obj.setRoomId(roomAndRack.getRoomId());
			    	 InventorySheetDetail detail = new InventorySheetDetail();
			    	 detail.setId(IdWorker.getId());
			    	 detail.setActualCabinet(Long.parseLong(roomAndRack.getRackId()));
			    	 detail.setInventorySheetId(inventorySheetId);
			    	 detail.setRackId(Long.parseLong(roomAndRack.getRackId()));
			    	 detail.setActualRoom(Long.parseLong(roomAndRack.getRoomId()));
			    	 detail.setActualU(obj.getU());
			    	 detail.setIsHandle(2);
			    	 detail.setStatus(5);
			    	 detail.setRfidNo(obj.getRfidNo());
			    	 detail.setCreateTime(new Date());
			    	 sheetDetail.add(detail);
		    	 }
		     }
		 }
		 //更新盘盈
		 if(sheetDetail!=null&&sheetDetail.size()>0) {
			 HashMap<String,Object> overMap = new HashMap<String,Object>();
			 overMap.put("overData", sheetDetail);
			 inventoryMapper.updateInventoryOver(overMap);
		 }
		 //更新正常
		 if(normalData!=null&&normalData.size()>0) {
			 HashMap<String,Object> normalMap = new HashMap<String,Object>();
			 normalMap.put("normalData", normalData);
			 normalMap.put("inventorySheetId", inventorySheetId);
			 inventoryMapper.updateInventoryNormal(normalMap);
		 }
		 
		 //更新差异
		 if(differentData!=null&&differentData.size()>0){
			 System.out.println(JSON.toJSONString(differentData));
			 for(Iterator<RfidState> iter = differentData.iterator(); iter.hasNext();){
		    	 RfidState obj = (RfidState) iter.next();
		    	 RfidState roomAndRack = itassetMapper.getRoomAndRack(obj.getRackConverCode());
		    	 obj.setRackId(roomAndRack.getRackId());
		    	 obj.setRoomId(roomAndRack.getRoomId());
		     }
			 HashMap<String,Object> differentMap = new HashMap<String,Object>();
			 differentMap.put("differentData", differentData);
			 differentMap.put("inventorySheetId", inventorySheetId);
			 inventoryMapper.updateInventoryDifferent(differentMap);
		 }
	}
	
	private void insertInventoryDetail(InventoryDetail detail) {
		inventoryMapper.insertInventoryDetail(detail);
		
	}
	
	private List<InventorySheetDetail> getInventoryAssets(Long rackId) {
		return inventoryMapper.getInventoryAssets(rackId);
	}

	public void edit(InventoryVo inventory) {
		//删除定时任务
		List<InventoryTime> timeList = inventoryMapper.getInventoryTimes(inventory.getId());
		if(timeList!=null&&timeList.size()>0) {
			for(InventoryTime o :timeList) {
				TaskScheduled task = new TaskScheduled();
				task.setTaskName(o.getId().toString());
				task.setTaskGroup("inventory");
				schedulerManager.delJob(task);
			}
		}
		
		inventoryMapper.deleteInventoryTime(inventory.getId());
		
		inventory.setUpdateTime(new Date());
		inventory.setUpdateBy(WebUtil.getCurrentUser());
		//更新盘点
		inventoryMapper.updateInventory(inventory);
		//删除盘点详情
		inventoryMapper.removeInventoryDetail(inventory.getId());	
		if (inventory.getInventoryTimes() != null && inventory.getInventoryTimes().size() > 0) {
			for (InventoryTime time : inventory.getInventoryTimes()) {
				time.setInventoryId(inventory.getId());
				time.setId(IdWorker.getId());
			}
			HashMap<String,Object> map=new HashMap<String,Object>();
			map.put("inventoryTimes", inventory.getInventoryTimes());
			inventoryMapper.insertInventoryTime(map);
		}
		for(Long rackId :inventory.getRackIds()){
			InventoryDetail detail = new InventoryDetail();
			detail.setId(IdWorker.getId());
			detail.setRackId(rackId);
			detail.setInventoryId(inventory.getId());
			detail.setCreateBy(WebUtil.getCurrentUser());
			detail.setCreateTime(new Date());
			insertInventoryDetail(detail);
		}
		//更新定时计划
		getTaxk(inventory);
	}


	public void remove(Long id) {
		//删除定时任务
		List<InventoryTime> timeList = inventoryMapper.getInventoryTimes(id);
		if(timeList!=null&&timeList.size()>0) {
			for(InventoryTime o :timeList) {
				TaskScheduled task = new TaskScheduled();
				task.setTaskName(o.getId().toString());
				task.setTaskGroup("inventory");
				schedulerManager.delJob(task);
			}
		}
		
		inventoryMapper.remove(id);
		inventoryMapper.removeInventoryDetail(id);
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public InventorySheet qryDetailById(Long sheetId) {
		InventorySheet vo = inventoryMapper.qrySheetObjById(sheetId);
		List<HashMap<String,Object>> countMap =inventoryMapper.qryInventoryCount(sheetId);
		if(countMap!=null&&countMap.size()>0){
			Integer total=0;
			for(HashMap<String,Object> map:countMap){
				Integer status = Integer.parseInt(map.get("status_")+"");
				Integer count = Integer.parseInt(map.get("count")+"");
				if(status==2){
					vo.setDifferent(count);
				}else if(status==3){
					vo.setNormal(count);
				}else if(status==4){
					vo.setLoss(count);
				}else if(status==5){
					vo.setOver(count);
				}
				total+=count;
			}
			vo.setTotalCount(total);
		}
		return vo;
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Page<InventorySheetDetail> quryAssetByInventory(Page<InventorySheetDetail> page, Map<String, Object> params) {
		List<InventorySheetDetail> list =inventoryMapper.quryAssetByInventory(page,params);
		page.setRecords(list);
		return page;	
	}

	/**
	 * 下达手动盘点命令
	 * @param id
	 */
	public void goInventory(Long id) {
		Inventory vo = inventoryMapper.qryById(id);
		//将盘点计划更新为执行中
		vo.setStatus(2);
		inventoryMapper.updateInventoryState(vo);
		//将盘点有关的数据先删除再添加   
		InventorySheet isheet =inventoryMapper.getInventorySheet(id);
		if(isheet!=null){
			inventoryMapper.deleteInventorySheet(isheet.getId());
			inventoryMapper.deleteInventorySheetDetail(isheet.getId());
		}
		
		InventorySheet sheet = new InventorySheet();
		sheet.setId(IdWorker.getId());
		sheet.setStatus(1);
		sheet.setExecuteTime(vo.getBeginTime());
		sheet.setInventoryId(vo.getId());
		sheet.setCreateBy(WebUtil.getCurrentUser());
		sheet.setCreateTime(new Date());
		String dateName= new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		sheet.setInventorySheetName(vo.getInventoryName()+dateName);
		//插入盘点单
		inventoryMapper.insertInventorySheet(sheet);
		//获取盘点计划详情列表
		List<InventoryDetail> dList =inventoryMapper.quryInDetail(id);
		if(dList!=null&&dList.size()>0){
			int rackUOrientation = PropertiesUtil.getInt("rackUOrientation", 1);
			for(InventoryDetail detail:dList){
				//循环查询出每个机柜内的设备，插入到盘点单详情里  (台账里的设备)
				List<InventorySheetDetail> shDetailList = null;
				if(rackUOrientation == 0) {
					shDetailList = getInventoryAssetsUfromAboveDown(detail.getRackId());
				}else {
					shDetailList = getInventoryAssets(detail.getRackId());
				}
				if(shDetailList!=null&&shDetailList.size()>0){
					for(InventorySheetDetail shdetail:shDetailList){
						shdetail.setId(IdWorker.getId());
						shdetail.setInventorySheetId(sheet.getId());
						shdetail.setLedgerCabinet(shdetail.getRackId());
						shdetail.setStatus(1);
						shdetail.setIsHandle(1);
					}
				}
				//批量插入盘点单详情
				HashMap<String,Object> map = new HashMap<String,Object>();
				map.put("shDetailList", shDetailList);
				inventoryMapper.insertInventorySheetDetail(map);
			}
		}
	}

	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	public Page<InventorySheet> qrySheetById(Page<InventorySheet> page, Map<String, Object> params) {
		List<InventorySheet> list =inventoryMapper.qrySheetById(page,params);
		page.setRecords(list);
		return page;	
	}

}
